﻿using Antlr.Runtime;
using Investment.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Teamwish.Domain.Common;
using Teamwish.Domain.DTOs;
using Teamwish.Domain.Models;
using Teamwish.Webapi.Filters;
using Teamwish.Webapi.Models;

namespace Teamwish.Webapi.Controllers
{
    [TokenAuthorize]
    public class WechatController : ApiController
    {
        private EfDbContext db = DIFactory.Resolve<EfDbContext>();

        /// <summary>
        /// 微信授权码登录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [AcceptVerbs("Get")]
        public SeverMsg CodeLogin(string code)
        {
            
            Dictionary<string, string> keyValues = WeChatHelper.GetOpenId("wx9cab8094d0c02340", "4b041ea86370c4a2b2637da9c357976f", code);
            string openid= keyValues["openid"];
            if (openid == null|| string.IsNullOrWhiteSpace(openid))
            {
                return new SeverMsg() { status = -1, message = "用户获取失败" };
            }
            Userinfo userinfo = db.Userinfo.AsNoTracking().Where(p => p.WxOpenId == openid).FirstOrDefault();          
            if (userinfo==null)
            {
                userinfo= new Userinfo();
                userinfo.WxOpenId = openid;
                userinfo.WxUnionId = keyValues["unionid"];
                db.Userinfo.Add(userinfo);
                db.SaveChanges();
            }
            string token = TokenHelper.GenToken(new TokenInfo()
            {
                iss = userinfo.Id.ToString(),
                UserId=userinfo.Id.ToString(),
                UserCode=userinfo.WxOpenId,
                UserName = "",
                UserRole = ""
                
            });
            //string token =Guid.NewGuid().ToString();
            Redis.RedisHelper.Set("token_weixin_"+ userinfo.Id, token,DateTime.Now.AddMinutes(2));
            
            return new SeverMsg() { status = 1, data =new { token,sessionId= userinfo.Id }  };
        }

        /// <summary>
        /// 更新微信用户信息
        /// </summary>
        /// <param name="userinfo"></param>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        [AcceptVerbs("POST")]
        public SeverMsg UpdateUserinfo(WxUserinfoDto userinfo)
        {
            SeverMsg msg =new SeverMsg() { status = -1 };
            //获取用户唯一用户id
            int? userId =int.Parse(PrincipalHelper.CurrentPrincipal.UserId);
            if (userId == null)
            {
                msg.message = "参数不正确";
                return msg;
            }
            Userinfo rowitem = db.Userinfo.Find(userId);
            if (rowitem == null)
            {
                msg.message = "参数不正确";
                return msg;
            }
            else
            {
                rowitem.WxGender = userinfo.Gender;
                rowitem.WxNickName = userinfo.NickName;
                rowitem.Province = userinfo.Province;
                rowitem.City = userinfo.City;
                rowitem.Country = userinfo.Country;
                rowitem.AvatarUrl = userinfo.AvatarUrl;
                db.SaveChanges();
                msg.status = 1;
            }        

            return msg;
        }

        /// <summary>
        /// 密码登录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [AcceptVerbs("Get")]
        public SeverMsg Login(string loginmame,string password)
        {
            SeverMsg msg = new SeverMsg() { status = -1 };
            var passwordMd5 = Teamwish.Utilities.Md5Helper.MD5(password, 32);
            Userinfo userinfo = db.Userinfo.AsNoTracking().Where(p => p.Username == loginmame&&p.Password== passwordMd5).FirstOrDefault();
            if (userinfo == null)
            {
                msg.status = -1;
                msg.message = "密码或用户名错误";
                return msg;
            }
            string token = Guid.NewGuid().ToString();
            Redis.RedisHelper.Set("token_web_" + userinfo.Id, token, DateTime.Now.AddMinutes(2));
            return new SeverMsg() { status = 1, data = token };
        }
    }
}
